import React, { useEffect, useState } from 'react'
import { Button, Drawer, Empty, Form, message, Space } from 'antd'
import useGetTableData from '@/hooks/useGetTableData'
import { delRoleById, getRoleList, addRole, updateRoleStatus } from '@/api/role'
import SearchForm from '@/components/CustomForm/SearchForm'
import { FormInstance, useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns } from './columns'
import { IOrgTableData, ITableData } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import { useFormAdd } from './useForm'
import CustomTable from '@/components/CustomTable'
import { AppListOptions, STATUSBANDOPTIONS, STATUSNUM } from '@/constant'
import { useNavigate } from 'react-router-dom'
import { getOrgListSearch } from '@/api/org'
import { useAppSelector } from '@/store/hooks'
import { PlusOutlined } from '@ant-design/icons'
import useCachePage from '@/hooks/useCachePage'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormEdit] = useForm()
  const [isModalShow, setIsModalShow] = useState(false)
  const [ispedding, setispedding] = useState<boolean>(false)
  const [orgOptions, setOrgOptions] = useState<IOptionItem[]>([])
  const [CreateOptions, setCreateOptions] = useState<IOptionItem[]>([])
  const orgId = useAppSelector((state) => state.user.user_info.orgId)
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, search, reset } = useGetTableData<ITableData>(getRoleList, {
    form: form,
    defaultFieldsParams: {
      orgId: orgId + '',
      status: 1,
    },
    immediatelySend: false,
  })
  let timeoutOrg: ITimeoutType
  useEffect(() => {
    handleSearchOrg()
    handleCacheData()
  }, [])
  const formatList = (list: ITableData[]): IOptionItem[] => {
    return list?.map((item: ITableData) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
        children: Array.isArray(item.children) ? formatList(item.children) : [],
      }
    })
  }
  const onConfirm = async (values: any) => {
    setispedding(true)
    const paramsData = {
      orgId: values?.org?.value,
      orgName: values?.org?.label,
      applicationId: values?.app?.value,
      applicationName: values?.app?.label,
      roleName: values.roleName,
      roleDesc: values.roleDesc,
    }
    const res = await addRole(paramsData).finally(() => setispedding(false))
    if (res.code === 200) {
      message.success('操作成功')
      onCancel()
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  const onCancel = () => {
    setIsModalShow(false)
    FormEdit.resetFields()
  }

  const onEdit = (id: number) => {
    navigate('/system/role/detail?id=' + id)
  }
  const onDel = async (id: number) => {
    const res = await delRoleById([id])
    if (res.code === 200) {
      message.success('操作成功')
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  const handleSearchOrg = (newValue = '') => {
    if (timeoutOrg) {
      clearTimeout(timeoutOrg)
      timeoutOrg = null
    }
    const getOptions = async () => {
      const res = await getOrgListSearch<IOrgTableData>({
        orgNameKeyWord: newValue,
      })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              ...item,
              label: item.name,
              value: item.id,
            }
          }) || []
        setOrgOptions(data)
      }
    }
    timeoutOrg = setTimeout(getOptions, 500)
  }
  const onStatus = async (info: ITableData) => {
    const res = await updateRoleStatus({
      status: info.status == STATUSNUM.CLOSE ? STATUSNUM.OPEN : STATUSNUM.CLOSE,
      id: info.id,
    })
    if (res.code === 200) {
      message.success('操作成功')
      console.log(params, 'params')
      search(params)
      // search({ orgId: form.getFieldValue('orgId') })
    }
  }
  const onOrgChange = (_: any, item: any) => {
    if (item?.id == 1) {
      setCreateOptions([...AppListOptions])
      return
    }
    if (item.applications && item.applications.length > 0) {
      FormEdit.setFieldValue('app', null)
      const options = AppListOptions?.filter((app) => item.applications?.includes(app.value))
      setCreateOptions(options)
    }
  }
  const onValuesChange = (changedValues: any, trimKeys: string[], form: FormInstance) => {
    trimKeys.forEach((key) => {
      if (changedValues[key]) {
        const trimmedKey = changedValues[key].trim()
        form.setFieldsValue({
          [key]: trimmedKey,
        })
      }
    })
  }
  const handleCacheData = () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      const paramsData = {
        ...params,
        orgId: orgId + '',
        status: 1,
      }
      search({
        ...paramsData,
      })
      setCachePage({
        ...paramsData,
      })
    } else {
      form.setFieldsValue({
        ...cacheData,
      })
      setOrgOptions(cacheData?.orgOptions || [])
      delete cacheData?.orgOptions
      search({
        ...cacheData,
        orgId: cacheData?.orgId != null ? cacheData.orgId : null,
      })
    }
  }
  return (
    <PageContainer className="rolemgr_page">
      <SearchForm
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['roleName'], form)}
        params={params}
        form={form}
        extra={
          <div className="table_extra_flex">
            <Button
              type="primary"
              onClick={() => {
                handleSearchOrg()
                setIsModalShow(true)
              }}
              icon={<PlusOutlined />}
            >
              新建角色
            </Button>
          </div>
        }
        searchConfig={[
          {
            label: '组织名称',
            name: 'orgId',
            type: 'Select',
            option: orgOptions,
            config: {
              suffixIcon: null,
              showSearch: true,
              optionFilterProp: 'label',
              filterOption: false,
              onSearch: handleSearchOrg,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          { label: '所属应用', name: 'applicationId', type: 'Select', option: AppListOptions },
          {
            label: '角色名称',
            name: 'roleName',
            type: 'Input',
          },
          { label: '角色状态', name: 'status', type: 'Select', option: STATUSBANDOPTIONS },
        ]}
        onFinish={(vals: any) => {
          const paramsData = {
            ...vals,
            orgId: vals.orgId != undefined ? vals.orgId : null,
            status: vals.status != undefined ? vals.status : null,
          }
          search(paramsData)
          setCachePage({
            ...paramsData,
            orgOptions,
            current: 1,
            size: params.size,
          })
        }}
        onReset={() => {
          const paramsData = {
            current: 1,
            size: 10,
            status: 1,
            orgId: orgId + '',
          }
          setCachePage({
            ...paramsData,
          })
          reset()
        }}
      ></SearchForm>
      <CustomTable bordered columns={useIndexColumns(onEdit, onDel, onStatus, params)} {...tableProps} />
      <Drawer
        title="新建角色"
        open={isModalShow}
        maskClosable
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button
                loading={ispedding}
                type="primary"
                onClick={() => FormEdit.validateFields().then((values) => onConfirm(values))}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          onValuesChange={(changedValues) => onValuesChange(changedValues, ['roleName', 'roleDesc'], FormEdit)}
          editConfig={useFormAdd({
            orgOptions,
            handleSearchOrg,
            AppListOptions,
            reset,
            onOrgChange,
            CreateOptions,
          })}
          form={FormEdit}
        />
      </Drawer>
    </PageContainer>
  )
}

export default Index
